var express = require('express')
var router = express.Router()
var path = require('path')
var fs = require('fs')
const { getAll, getById, exec } = require('../db/index')

//引入保存文件的模块
//导入multer文件上传对象和实例化
let multer = require('multer')
// let upload = multer({ dest: 'uploads/' }) //uploads是创建的文件夹,没有会主动创建

/*
  multer是node的中间件, 处理表单数据 主要用于上传文件  multipart/form-data
*/
// ----------------------------------------------------
// 指定存储位置
const storage = multer.diskStorage({
  // 存储位置
  destination(req, file, callback) {
    // 参数一 错误信息   参数二  上传路径（此处指定upload文件夹）
    callback(null, 'upload')
  },
  // 确定文件名
  filename(req, file, cb) {
    cb(null, Date.now() + file.originalname)
  },
})

// 得到multer对象  传入storage对象
const upload = multer({ storage })
// .................................................

// 解构调试的的标记,将来会根据这个决定是否发送错误信息
const { debug } = require('../config/index')




//上传照片功能
// 挂载中间件
router.post('/', upload.single('file'), (req, res) => {
  // 需要返回图片的访问地址    域名+文件名
  const url = 'http://localhost:3000/' + 'upload/' + req.file.filename
  res.json({ url })
  // console.log(res.json({ url }))
})

// 根据id获取一片文章
router.get('/:id', async (req, res) => {
  // 解析请求参数
  const { id } = req.params
  let sql = `select * from articles where id = ${id}`

  try {
    const data = await getById(sql)
    // console.log(data) //返回的是一个数组,
    res.send({
      code: 0,
      message: '根据id获取文章成功',
      result: { data },
    })
  } catch (error) {
    res.send({
      code: 100101,
      message: '根据id获取文章失败',
      result: debug ? error : '',
    })
  }
})



//删除图片数据库图片地址清空

router.delete('/:id', async function (req, res) {
  //1,获取请求的参数
  const id = req.params.id
  //2,编写sql语句
  let sql = `update  articles set iamge_address = ""  where id=${id}`
  //执行sql语句,返回结果
  try {
    const data = await exec(sql)
    res.send({
      code: 0,
      message: '删除图片地址成功',
      result: '',
    })
  } catch (error) {
    res.send({
      code: 100108,
      message: '删除图片地址失败',
      result: debug ? error : '',
    })
  }
})



//删除图片
router.post('/delimg', async function (req, res) {
  //1,获取请求的参数--带问号的参数
  const { imgUrl } = req.body

  console.log(imgUrl)
  // // url转换成数组

  const imgUrlArr = imgUrl.split('/')
  console.log(imgUrlArr)
  const lastPath =
    imgUrlArr[imgUrlArr.length - 2] + '/' + imgUrlArr[imgUrlArr.length - 1]
  console.log(lastPath)

  const imgName = imgUrlArr[imgUrlArr.length - 1]
  // --------------------删除文件里面的照片

  fs.unlink(lastPath, (err) => {
    if (err) {
      console.log(err)
      res.send({
        status: 1,
        msg: '删除文件失败',
      })
    } else {
      res.send({
        status: 0,
        msg: '删除文件成功',
      })
    }
  })
  // -----------
})

//新增文章功能
//新增代办
//获取一个代办//post/todo {content:"test"}  返回(新增的数据){}
router.post('/add', async function (req, res) {
  console.log(req.body)
  //1,获取请求的参数
  const { title, author, keywords, cate_id, content, iamge_address } = req.body

  //2,编写sql语句
  let sql = `insert into articles (title, author, keywords,cate_id, content, iamge_address) values
   ('${title}','${author}','${keywords}','${cate_id}','${content}','${iamge_address}')`
  //3,执行sql语句,返回结果
  console.log(sql)
  try {
    const data = await exec(sql)
    res.send({
      code: 0,
      message: '添加文章成功',
      result: data,
    })
  } catch (error) {
    res.send({
      code: 100105,
      message: '添加文章失败',
      result: debug ? error : '',
    })
  }
})

//put /users/id {username:'new',password:'new'}
router.put('/:id', async function (req, res) {
  //1,获取请求的参数
  const id = req.params.id
  const { title, author, keywords, cate_id, content, iamge_address } = req.body
  // ('${title}','${author}','${keywords}','${cate_id}','${content}','${iamge_address}')`
  //2,编写sql语句
  let sql = `update articles set title='${title}',author='${author}',keywords='${keywords}',cate_id='${cate_id}',content='${content}',iamge_address='${iamge_address}' where id = ${id}`
  console.log(sql)
  //3,执行sql语句,返回结果
  try {
    const data = await exec(sql)
    res.send({
      code: 0,
      message: '修改文章成功',
      result: {
        data,
      },
    })
  } catch (error) {
    res.send({
      code: 100107,
      message: '修改文章失败',
      result: debug ? error : '',
    })
  }
})

module.exports = router
